//
//  JLFlutterPluginOtaManager.m
//  flutter_jl_bluetooth_plugin
//
//  Created by 凌煊峰 on 2021/7/28.
//

#import "JLFlutterPluginOtaManager.h"
#import "JLFlutterBluetoothPluginNotificationConst.h"
#import <JL_BLEKit/JL_BLEKit.h>

@interface JLFlutterPluginOtaManager (){
    JL_ManagerM *mCmdManager;
}

// OTA升级相关
@property (strong, nonatomic) NSData *otaData;
@property (strong, nonatomic) NSArray<NSString *> *otaFileArray;

@end

@implementation JLFlutterPluginOtaManager

+ (instancetype)sharedInstance {
    static JLFlutterPluginOtaManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
        [instance addNote];
    });    
    return instance;
}

- (void)addNote {
    // ota升级相关
    [JL_Tools add:kFLT_BLE_OTA Action:@selector(noteOtaUpdate:) Own:self];
}

- (void)setOtaUpgradeFileDocPath:(NSString *)otaUpgradeFileDocPath {
    _otaUpgradeFileDocPath = [NSString stringWithString:otaUpgradeFileDocPath];
    NSString *docPath = [JL_Tools listPath:NSDocumentDirectory MiddlePath:_otaUpgradeFileDocPath File:@""];
    _otaFileArray = [JL_Tools subPaths:docPath];
}

#pragma mark - 通知 - ota升级相关

- (void)getBleDeviceInfoWithStartOtaUpgrade:(BOOL)startOtaUpgrade {
    /*--- 获取设备信息 ---*/
    mCmdManager = self.mBLEManager.mAssist.mCmdManager;
    
    [mCmdManager cmdTargetFeatureResult:^(NSArray *array) {
        JL_CMDStatus st = [array[0] intValue];
        if (st == JL_CMDStatusSuccess) {
            [self noteOtaUpdate:nil];
        } else {
            NSLog(@"---> 错误提示：%d", st);
        }
    }];
}

- (void)noteOtaUpdate:(NSNotification*)note {
    if (_selectOtaFilePath == nil || _selectOtaFilePath.length == 0) return;
    _otaData = [NSData dataWithContentsOfFile:_selectOtaFilePath];
    
    [mCmdManager cmdOTAData:self.otaData Result:^(JL_OTAResult result, float progress) {
        if (result == JL_OTAResultUpgrading || result == JL_OTAResultPreparing) {

            
            if (result == JL_OTAResultPreparing) {
                if (self.eventSink) self.eventSink(@{@"EventName" : JLOTAUPGRADEPREPARING, @"EventObject": @{@"progress": [NSNumber numberWithDouble:progress]}});

            } else if (result == JL_OTAResultUpgrading) {
                if (self.eventSink) self.eventSink(@{@"EventName" : JLOTAUPGRADING, @"EventObject": @{@"progress": [NSNumber numberWithDouble:progress]}});

            }
//            [self otaTimeCheck];//增加超时检测
        } else if(result == JL_OTAResultPrepared) {
            NSLog(@"OTA is ResultPrepared...");
            if (self.eventSink) self.eventSink(@{@"EventName" : JLOTAUPGRADEPREPARED, @"EventObject": [NSNumber numberWithBool:YES]});
//            [self otaTimeCheck];//增加超时检测
        } else if(result == JL_OTAResultReconnect) {
//            [self otaTimeClose];//关闭超时检测
            if (self.eventSink) self.eventSink(@{@"EventName" : JLOTABLEDEVICERECONNECT, @"EventObject": [NSNumber numberWithBool:YES]});
            
            /*--- 重连设备 ---*/
            [self.mBLEManager connectPeripheralWithUUID:self.mBLEManager.lastUUID];

        } else if (result == JL_OTAResultSuccess) {
            NSLog(@"OTA 升级完成.");
            if (self.eventSink) self.eventSink(@{@"EventName" : JLOTAUPGRADESUCCESS, @"EventObject": [NSNumber numberWithBool:YES]});

        } else if (result == JL_OTAResultReboot) {
            NSLog(@"OTA 设备准备重启.");
//            [DFUITools showText:kJL_TXT("设备准备重启") onView:self.view delay:1.0];
            if (self.eventSink) self.eventSink(@{@"EventName" : JLOTABLEDEVICEREADYTORESTART, @"EventObject": [NSNumber numberWithBool:YES]});
            [JL_Tools delay:1.5 Task:^{
                [JL_Manager bleConnectLastDevice];
            }];
        } else if (result == JL_OTAResultFailCompletely) {
            if (self.eventSink) self.eventSink(@{@"EventName" : JLOTAUPGRADEFAILED, @"EventObject": [NSNumber numberWithBool:YES]});
//            self.updateTxt.text = kJL_TXT("升级失败");
//            [DFUITools showText:kJL_TXT("升级失败") onView:self.view delay:1.0];
//
//            [DFAction delay:1.5 Task:^{
//                [self isUpdatingUI:NO];
//            }];
        } else if (result == JL_OTAResultFailKey) {
            if (self.eventSink) self.eventSink(@{@"EventName" : JLOTAUPGRADEFILEKEYERROR, @"EventObject": [NSNumber numberWithBool:YES]});
//            self.updateTxt.text = kJL_TXT("升级文件KEY错误");
//            [DFUITools showText:kJL_TXT("升级文件KEY错误") onView:self.view delay:1.0];
//
//            [DFAction delay:1.5 Task:^{
//                [self isUpdatingUI:NO];
//            }];
        } else if (result == JL_OTAResultFailErrorFile) {
            if (self.eventSink) self.eventSink(@{@"EventName" : JLOTAUPGRADEFILEERROR, @"EventObject": [NSNumber numberWithBool:YES]});
//            self.updateTxt.text = kJL_TXT("升级失败");
//            [DFUITools showText:kJL_TXT("升级失败") onView:self.view delay:1.0];
//
//            [DFAction delay:1.5 Task:^{
//                [self isUpdatingUI:NO];
//            }];
        } else {
//            [self otaTimeClose];//关闭超时检测
            if (self.eventSink) self.eventSink(@{@"EventName" : JLOTAUPGRADECLOSEOVERTIMECHECK, @"EventObject": [NSNumber numberWithBool:YES]});
        }
    }];
}

@end
